#!/usr/bin/env lua
--this script is used to detect http server and the web application version

http = require('socket.http')
html = require('html')

function usage()
    print('usage: lua http_version_detect.lua [ip or http://localhost]')
end

--this function is used to find a str from html content and print it
--it may print a haft string, because it find a string in a html element
function findStrFromHtml(content, str)
    for k,v in pairs(content) do
        if k == '_attr' then
            for k1,v1 in pairs(v) do
                if string.match(v1, str) ~= nil then
                    print(v1)
                    return
                end
            end
        elseif k ~= '_tag' and type(v) == 'string' then
            if string.match(v, str)  ~= nil then
                print(v)
                return
            end
        elseif type(v) == 'table' then
            findStrFromHtml(v, str)
        end
    end
end

function luamain(url)
--[[
    if arg[1] == nil or string.len(arg[1]) == 0 then
        print('The number of arguments is not right')
        usage()
        return
    end
    if string.match(arg[1], '^http://') == nil then
        arg[1] = 'http://' .. arg[1]
    end

    local r,c,h = http.request( arg[1] )
    --]]
--    local url = "http://www.sina.com.cn"
    local r,c,h = http.request( url )
    if c == 200 then
        if h['x-powered-by'] ~= nil then
            print("powered by " .. h['x-powered-by'])
        end
        --print(h['date'])
        local content = http.request( url )
        content = string.lower(content)
        if string.match(content, 'test page for .* fedora') ~= nil then
            print('Fedora Default Page')
        elseif string.match(content, 'placeholder page') ~= nil then
            print('Debian Default Page')
        elseif string.match(content, 'welcome to windows small business server (%d+)') ~= nil then
            print('Windows SBS')
        elseif string.match(content, 'asterisk@home') ~= nil then
            print('Asterix')
        elseif string.match(content, 'swfs/shell.html') ~= nil then
            print('BPS-1000')
        elseif string.match(content, 'powered by') ~= nil then
            local content_table = html.parsestr(content)
            findStrFromHtml(content_table, 'powered by')
        end
        --[[      
        for k,v in pairs(h) do
        print(k .. ':' .. v)
        end
        --]]
    end
    return 0
end

--main()
